package com.ljyhhh.SmartCity.utils

import android.content.Context
import android.util.Log
import com.ljyhhh.SmartCity.base.user.User
import java.io.File

class TextDatePersistence(context: Context){
    private val filePath:String
    init {
        filePath = context.getExternalFilesDir(null)?.absolutePath + File.separator + "user.txt"
    }
    fun checkAutoLogin(): Boolean {

        if(!File(filePath).exists()){
            Log.d("file---","false")
            return false
        }
        return try{
            val text=File(filePath).readText()
            text.split("----")[0] == "1"
        }catch (e:Exception){
            Log.d("eroor",e.toString())
            false
        }

    }

    fun userTextRead(): User? {
        if(!File(filePath).exists()){
            Log.d("file---","false")
            return null
        }
        return try {
            val text=File(filePath).readText()
            val textList=text.split("----")
            User(username = textList[1], password = textList[2])
        }catch (e:Exception){
            Log.d("eroor",e.toString())
            null
        }

    }
    fun userTextWrite(user: User, autoLogin:Boolean){
        if(!File(filePath).exists()){
            Log.d("file---","false")
        }
        val text="${if(autoLogin) '1' else '0'}----${user.username}----${user.password}"
        File(filePath).writeText(text)
    }
}